package main

import (
	. "gini2p/config"
	"gini2p/logger"
	"gini2p/middleware"
	"gini2p/models"
	"gini2p/router"
	"gini2p/utility"
	"strconv"
	"strings"

	"fmt"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func main() {
	defer utility.PacnicStack()

	//初始化配置信息
	InitConfig()

	//设置日志前台可见
	consoleFlag := false
	if strings.EqualFold(Log.IsConsole, "1") {
		consoleFlag = true
	}
	logger.SetConsole(consoleFlag)

	//根据日志文件设置日志等级
	loglevel := logger.ERROR
	switch Log.Level {
	case "Debug":
		loglevel = logger.DEBUG
	case "Info":
		loglevel = logger.INFO
	case "Warn":
		loglevel = logger.WARN
	case "Fatal":
		loglevel = logger.FATAL
	}
	logger.SetLevel(loglevel)
	//根据配置文件设置　日志路径，日志名，日志切割大小限制
	num, err := strconv.Atoi(Log.Num)
	if err != nil {
		num = 10
	}

	max, err := strconv.Atoi(Log.Max)
	if err != nil {
		max = 50
	}

	logger.SetRollingFile(Log.Path, int32(num), int64(max), logger.MB)

	//初始化gin服务
	serv := gin.New()

	store, err := sessions.NewRedisStore(10, "tcp", "127.0.0.1:6379", "", []byte("secret"))

	if err != nil {
		logger.Error("app", fmt.Sprint(err))
	}

	serv.Use(sessions.Sessions("mysession", store))

	err = models.InitSql()
	if err != nil {
		logger.Error("app", fmt.Sprint("初始化数据库连接失败:", err))
		return
	}
	//go ticker.RecongnizeRate()
	middleware.Init(serv)
	router.Init(serv)
	serv.Run(Server.IP + ":" + Server.Port)
}
